<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use Illuminate\Support\Facades\Redis;
use App\Models\NoticeLog;

class NoticeRedisCommand extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'notice:exec';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '执行当天的提醒';

    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle()
    {
        $redis = Redis::hGetAll(NoticeCommand::RedisNoticeKey);

        $now = now();
        foreach($redis as $k=>$v) {
            // 超过30分钟，则不提醒
            if ($now->timestamp >= intval($k) && $now->timestamp < (intval($k) + 30*60)) {
                // 触发提醒弹框
                $data = unserialize($v);
                [$output, $return] = $this->sendNotice($data);
                // 删除
                Redis::hdel(NoticeCommand::RedisNoticeKey, $k);
                // 记录日志
                $log = new NoticeLog();
                $log->notice_id = $data['id'];
                $log->remote_ip = $data['remote_ip'];
                $log->output = serialize($output);
                $log->return = serialize($return);
                $log->notice_time = now();
                $log->save();
            }
        }

        return 0;
    }

    public function sendNotice($data)
    {
        $date = date('Ymd');
        $key = $data['remote_ip'] ? md5($data['remote_ip']) : md5(time() . rand(1000,9999));
        $dir = 'app/notice/tmp/' . $date;
        $file = storage_path($dir . '/' . $key . '.vbs');

        $site = [];
        foreach ($data['content'] as $value) {
            // 
            $title = iconv("UTF-8", "GBK//IGNORE", $value['title']);
            $content = iconv("UTF-8", "GBK//IGNORE", $value['value']);
            $site[] = 'x=msgbox("'.$content.'",' . $data['notice_type'] . ',"'.$title.'")';
        }

        $site = implode(PHP_EOL,$site);

        if (!is_dir(storage_path($dir))) {
            mkdir(storage_path($dir), 0777, true);
        }
        file_put_contents($file, $site, LOCK_EX);

        exec($file, $output, $return);

        return [$output,$return];
    }
}
